package com.jintu.portal.config;

import com.jintu.portal.cache.RedisHelper;
import com.jintu.portal.repository.mysql.dao.SysConfigDao;
import com.jintu.portal.pojo.exception.DaoException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.lang.NonNull;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author very
 */
@Slf4j
@Service("sysConfigWatcher")
@DisallowConcurrentExecution
public class SysConfigWatcher extends QuartzJobBean {

    private static String CURRENT_SYS_CONFIG_VERSION = "";

    @Resource(name = "redisHelper")
    private RedisHelper redisHelper;

    @Resource(name = "sysConfigurer")
    private SysConfigurer sysConfiger;

    @Resource(name = "sysConfigDao")
    private SysConfigDao sysConfigDao;

    @Override
    protected void executeInternal(@NonNull JobExecutionContext jobExecutionContext) {
        String redisSysConfigVersion = redisHelper.get(Constant.SYS_CONFIG_VERSION_REDIS_KEY);
        if(StringUtils.isBlank(redisSysConfigVersion)){
            log.debug("Redis系统配置版本为空。");
        } else {
            if(!redisSysConfigVersion.equals(CURRENT_SYS_CONFIG_VERSION)){
                log.info("系统配置版本更新从[{}]更新为[{}]，risk-gateway配置更新。", CURRENT_SYS_CONFIG_VERSION, redisSysConfigVersion);
                try {
                    sysConfiger.updateProps(sysConfigDao.queryAllSysConfig());
                    CURRENT_SYS_CONFIG_VERSION = redisSysConfigVersion;
                } catch (DaoException e) {
                    log.error("系统配置版本更新从[{}]更新为[{}]更新失败", CURRENT_SYS_CONFIG_VERSION, redisSysConfigVersion);
                    log.error(e.getMessage(), e);
                }
            }
        }
    }
}
